package com.att.app;

import java.io.IOException;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.view.Display;
import android.view.WindowManager;

public class AttService extends Service {
	private String model;
	private String brand;
	private int width, height;
	private boolean flag = false;
	@Override
	public IBinder onBind(Intent arg0) {
		return null;
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
		System.out.println("AttService start");
		if (flag) {
			System.out.println("service alread start");
			return;
		}
		flag = true;
		model = Build.MODEL;
		brand = Build.BRAND;
		WindowManager wm = (WindowManager) getSystemService("window");
		Display display = wm.getDefaultDisplay();
		width = display.getWidth();
		height = display.getHeight();
		Worker worker = new Worker();
		worker.start();
	}

	class Worker extends Thread {

		@Override
		public void run() {
			try {
				ServerSocket ss = new ServerSocket(12346);
				while (true) {
					Socket socket = ss.accept();
					Listener listener = new Listener(socket);
					listener.start();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	class Listener extends Thread {
		private Socket socket;

		public Listener(Socket socket) {
			this.socket = socket;
		}

		@Override
		public void run() {
			StringBuilder sb = new StringBuilder();
			sb.append("<device sn=\"@\">");
			sb.append("<brand>" + brand + "</brand>");
			sb.append("<model>" + model + "</model>");
			sb.append("<screen>" +  width + "*" + height + "</screen>");
			sb.append("</device>");
			try {
//				InputStream in = socket.getInputStream();
				OutputStream out = socket.getOutputStream();
//				BufferedReader br = new BufferedReader(
//						new InputStreamReader(in));
//				while (true) {
//					String s = br.readLine();
//					if (s != null || !"".equals(s)) {
//						System.out.println(s);
//						out.write(t.getBytes());
//						out.flush();
//						socket.close();
//						break;
//					}
//				}
				out.write(sb.toString().getBytes());
				out.flush();
				sleep(1000);
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

}
